﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using YLClient.YLServiceClient;
using YLPublicService.TransferModel;

namespace YLClient.BLL
{
    public class WorkItemManager
    {
        ServiceClient serviceClient = ServiceClient.GetServiceClient();
        IEnumerable<IWorkItem> workItemsCache;
        public IEnumerable<IWorkItem> GetIWorkItems()
        {
            if (workItemsCache != null)
            {
                return workItemsCache;
            }
            var wis = serviceClient.GetWorkItems();
            //封装为拓展的工作项
            var workitems = wis
                .Select(wi =>
                    new WorkItemEx(wi));
            workItemsCache = workitems;
            return workItemsCache;
        }

        public IEnumerable<IWorkItem> GetIWorkItemsByRequireValues(TemplateItem templateItem)
        {
            Dictionary<string, string> srcRequireValues = new Dictionary<string, string>();
            foreach (var v in templateItem.mTemplateDetial.mRequireValues.mItem)
            {
                srcRequireValues[v.mMemo] = v.mValue;
            }
            var neededkvs = from kv in templateItem.mTemplateDetial.mRequireValues.mItem
                            where kv.mValue != string.Empty
                            select Tuple.Create(kv.mMemo, kv.mValue);

            var tid = Convert.ToInt32(templateItem.mID);
            var workItems = GetIWorkItems();

            var wis = from wi in workItems
                      where wi.TemplateID == tid
                      where matchRequireValues(srcRequireValues, neededkvs)
                      select wi;

            return wis;
        }

        bool matchRequireValues(Dictionary<string, string> srcRequireValues, IEnumerable<Tuple<string, string>> keyValues)
        {
            bool match = true;
            foreach (var kv in keyValues)
            {
                if (srcRequireValues[kv.Item1] != kv.Item2)
                {
                    match = false;
                    return match;
                }
            }
            return match;
        }
    }
}
